from itertools import count

from flask import Flask, render_template, request, jsonify
from flask import redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from exts import db

import pymysql
import json

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:Lihao@997@127.0.0.1/iclrbbn'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)


class association(db.Model):
    __tablename__ = 'association'
    id = db.Column(db.Integer, primary_key=True)
    disease = db.Column(db.String(255))
    LncRNA = db.Column(db.String(255))
    score = db.Column(db.Float(255))


@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template('home.html')


@app.route('/LncRNA/', methods=['GET', 'POST'])
def LncRNA():
    # conn = pymysql.connect(host='127.0.0.1', user='root', password='lihao997', db='iclrbbn', charset='utf8')
    # cur = conn.cursor()
    # sql = "SELECT * FROM association"
    # cur.execute(sql)
    # association1 = cur.fetchall()
    # conn.close()
    # if request.method == 'POST':
    lncrna = request.values.get("lncrna")
    # print(lncrna)

    if request.method == 'POST':
        association1 = association.query.filter(association.LncRNA.like("%{0}%".format(lncrna))).all()


        # return render_template('LncRNA.html', association1=association1)

        payload = []
        content = {}
        for result in association1:
            content = {'disease': result.disease, 'LncRNA': result.LncRNA, 'score': result.score}
            payload.append(content)
            content = {}
        association2 = jsonify(payload)
        data1 = {
            "code": 0,
            "msg": "",
            "count": len(association1),
            "data": payload,
        }
        json_str = json.dumps(data1)
        with open("./static/params.json", "w", encoding='UTF-8') as f:
            json.dump(json_str, f)
        flag = 1
        if data1['count'] == 0:
            flag = 0
        return render_template('LncRNA.html', association1=association1, lncrna=lncrna)
    else:
        data1 = {
            "code": 0,
            "msg": "",
            "count": 0,
            "data": [],
        }
        json_str = json.dumps(data1)
        with open("./static/params.json", "w", encoding='UTF-8') as f:
            json.dump(json_str, f)
        return render_template('LncRNA.html')


@app.route('/Disease/', methods=['GET', 'POST'])
def Disease():
    disease = request.values.get("disease")
    # print(lncrna)

    if request.method == 'POST':
        association1 = association.query.filter(association.disease.like("%{0}%".format(disease))).all()

        payload = []
        content = {}
        for result in association1:
            content = {'disease': result.disease, 'LncRNA': result.LncRNA, 'score': result.score}
            payload.append(content)
            content = {}
        association2 = jsonify(payload)
        data1 = {
            "code": 0,
            "msg": "",
            "count": len(association1),
            "data": payload,
        }
        json_str = json.dumps(data1)
        with open("./static/params.json", "w", encoding='UTF-8') as f:
            json.dump(json_str, f)
        flag = 1
        if data1['count'] == 0:
            flag = 0
        return render_template('Disease.html', association1=association1, disease=disease)
    else:
        data1 = {
            "code": 0,
            "msg": "",
            "count": 0,
            "data": [],
        }
        json_str = json.dumps(data1)
        with open("./static/params.json", "w", encoding='UTF-8') as f:
            json.dump(json_str, f)
        return render_template('Disease.html')


@app.route('/tabledata/', methods=['GET', 'POST'])
def tabledata():
    with open("./static/params.json", encoding="utf-8") as load_f:
        json_str = json.load(load_f)
    json_str = eval(json_str)
    return json_str


@app.route('/lncflag/', methods=['GET', 'POST'])
def lncflag():
    with open("./static/params.json", encoding="utf-8") as load_f:
        json_str = json.load(load_f)
    json_str = eval(json_str)
    print(json_str, type(json_str))
    # flag = json_str["count"]
    return json_str


@app.route('/Contact')
def Contact():
    return render_template('contact.html')


@app.route('/Help')
def Help():
    return render_template('help.html')


@app.route('/Download')
def Download():
    return render_template('downloads.html')


if __name__ == '__main__':
    app.run(debug=True)
